package ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ThreadLocalRandom;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToolBar;
import javax.swing.WindowConstants;

public class MainFrame extends JFrame {

	private JButton startBt;
	private JButton stopBt;
	private JButton ruleBt;
	private JButton aboutBt;
	private JSlider progressSlider;
	private JLabel amountLabel;

	private int speed = 0;
	private int foodNum;
	private int xHead;
	private int yHead;
	private int[][] xyMatrix = new int[75][38];
	private int[] xSnake = new int[2739];
	private int[] ySnake = new int[2739];
	private int snakeLength = 0;

	private boolean stop, space;

	private String keyDirection = new String();
	private String snakeDirection = new String();

	private ThreadLocalRandom xyRandom = ThreadLocalRandom.current();

	public MainFrame() {
		this.setTitle("GluttonousSnake(贪吃蛇)");
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		Toolkit tool = Toolkit.getDefaultToolkit();// 创建系统该默认组件工具包
		Dimension d = tool.getScreenSize();// 获取屏幕尺寸，赋给一个二维坐标对象
		this.setSize(d.width - d.width / 5 - 1, d.height - d.height / 5 + 1);// 设置窗体大小
		this.setResizable(false);
		// 让主窗体在屏幕中间显示
		this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);

		uiInit();

		Timer timer = new Timer();
		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				if (!stop) {
					try {
						Thread.sleep(250 - speed);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					repaint();
				}
			}
		};
		timer.schedule(task, 0, 100);

		addActionListener();
	}

	private void uiInit() {
		JToolBar toolBar = new JToolBar("工具栏");
		toolBar.addSeparator(new Dimension(15, 0));
		startBt = new JButton("开始游戏");
		toolBar.add(startBt);
		toolBar.addSeparator(new Dimension(15, 0));
		stopBt = new JButton("暂停游戏");
		stopBt.setEnabled(false);
		toolBar.add(stopBt);
		toolBar.addSeparator(new Dimension(15, 0));
		ruleBt = new JButton("游戏规则");
		toolBar.add(ruleBt);
		toolBar.addSeparator(new Dimension(15, 0));
		aboutBt = new JButton("开发人员");
		toolBar.add(aboutBt);
		toolBar.addSeparator(new Dimension(15, 0));
		toolBar.add(new JLabel("游戏进度："));
		toolBar.addSeparator(new Dimension(10, 0));
		progressSlider = new JSlider();
		progressSlider.setMaximum(74 * 37);
		progressSlider.setValue(0);
		toolBar.add(progressSlider);
		toolBar.addSeparator(new Dimension(10, 0));
		amountLabel = new JLabel("现在长度：0000");
		toolBar.add(amountLabel);
		progressSlider.setEnabled(false);
		toolBar.addSeparator(new Dimension(10, 0));
		toolBar.setFloatable(false);

		startBt.setFocusable(false);
		stopBt.setFocusable(false);
		ruleBt.setFocusable(false);
		aboutBt.setFocusable(false);

		toolBar.setFocusable(false);

		JPanel paintPanel = new JPanel() {

			@Override
			public void paint(Graphics g) {
				super.paint(g);
				// 绘制网格
				for (int x = 0; x <= 1480; x += 20) {
					g.drawLine(x, 0, x, this.getHeight());
				}
				for (int y = 0; y <= 740; y += 20) {
					g.drawLine(0, y, this.getWidth(), y);
				}

				if (startBt.getText().equals("结束游戏")) {
					// 方向控制
					if (keyDirection.equals("上")) {
						if (!"下".equals(snakeDirection))
							snakeDirection = "上";
					} else if (keyDirection.equals("下")) {
						if (!"上".equals(snakeDirection))
							snakeDirection = "下";
					} else if (keyDirection.equals("左")) {
						if (!"右".equals(snakeDirection))
							snakeDirection = "左";
					} else if (keyDirection.equals("右")) {
						if (!"左".equals(snakeDirection))
							snakeDirection = "右";
					} else {
						snakeDirection = "";
					}

					// 删除蛇尾部的坐标
					xyMatrix[xSnake[snakeLength - 1]][ySnake[snakeLength - 1]] = 0;

					// 蛇移动
					if (snakeDirection.equals("上")) {
						yHead -= 1;
						if (yHead <= 0)
							yHead = 37;
					} else if (snakeDirection.equals("下")) {
						yHead += 1;
						if (yHead >= 38)
							yHead = 1;
					} else if (snakeDirection.equals("左")) {
						xHead -= 1;
						if (xHead <= 0)
							xHead = 74;
					} else if (snakeDirection.equals("右")) {
						xHead += 1;
						if (xHead >= 75)
							xHead = 1;
					}

					// 蛇移动后的坐标
					for (int i = snakeLength - 1; i > 0; i--) {
						xSnake[i] = xSnake[i - 1];
						ySnake[i] = ySnake[i - 1];
					}
					xSnake[0] = xHead;
					ySnake[0] = yHead;

					// 如果设吃到食物
					if (xyMatrix[xHead][yHead] == 2) {
						foodNum--;
						xSnake[snakeLength] = xHead;
						ySnake[snakeLength] = yHead;
						snakeLength++;
					} else if (xyMatrix[xHead][yHead] == 1) {// 如果蛇咬到自己 把这个注释可以无敌
						startBt.doClick();
						return;
					}

					// 设置设移动后的坐标
					for (int i = 0; i < snakeLength; i++) {
						if (i == 0) {
							xyMatrix[xSnake[i]][ySnake[i]] = 3;
						} else {
							xyMatrix[xSnake[i]][ySnake[i]] = 1;
						}
					}

					// 放置食物
					if (foodNum < 8) {
						int xfood = xyRandom.nextInt(1, 74);
						int yfood = xyRandom.nextInt(1, 37);
						if (xyMatrix[xfood][yfood] != 1) {
							xyMatrix[xfood][yfood] = 2;
							foodNum += 1;
						}
					}
				}

				// 绘制颜色方格
				for (int x = 1; x <= 74; x++) {
					for (int y = 1; y <= 37; y++) {
						if (xyMatrix[x][y] == 1) {
							g.setColor(Color.RED);
						} else if (xyMatrix[x][y] == 0) {
							g.setColor(Color.WHITE);
						} else if (xyMatrix[x][y] == 2) {
							g.setColor(Color.GREEN);
						} else if (xyMatrix[x][y] == 3) {
							g.setColor(Color.BLUE);
						}
						g.fillRect((x - 1) * 20 + 1, (y - 1) * 20 + 1, 20 - 1, 20 - 1);
					}
				}

				String strLength = String.valueOf(snakeLength);
				if (strLength.length() == 1) {
					amountLabel.setText("现在长度：000" + strLength);
				} else if (strLength.length() == 2) {
					amountLabel.setText("现在长度：00" + strLength);
				} else if (strLength.length() == 3) {
					amountLabel.setText("现在长度：0" + strLength);
				} else {
					amountLabel.setText("现在长度：" + strLength);
				}

				if (!space) {
					if (snakeLength <= 10) {
						speed = 50;
					} else if (snakeLength > 10 && snakeLength <= 20) {
						speed = 100;
					} else if (snakeLength > 20 && snakeLength <= 30) {
						speed = 150;
					} else if (snakeLength > 30 && snakeLength <= 40) {
						speed = 200;
					} else if (snakeLength > 40) {
						speed = 250;
					}
				}

				if (snakeLength == 74 * 37) {
					startBt.doClick();
					return;
				}

				progressSlider.setValue(snakeLength);
			}
		};

		this.add(toolBar, BorderLayout.NORTH);
		this.add(paintPanel, BorderLayout.CENTER);
	}

	private void addActionListener() {
		KeyAdapter keyProcessor = new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent key) {
				if (key.getKeyCode() == KeyEvent.VK_UP || key.getKeyCode() == KeyEvent.VK_W) {
					keyDirection = "上";
				} else if ((key.getKeyCode() == KeyEvent.VK_DOWN || key.getKeyCode() == KeyEvent.VK_S)) {
					keyDirection = "下";
				} else if ((key.getKeyCode() == KeyEvent.VK_LEFT || key.getKeyCode() == KeyEvent.VK_A)) {
					keyDirection = "左";
				} else if ((key.getKeyCode() == KeyEvent.VK_RIGHT || key.getKeyCode() == KeyEvent.VK_D)) {
					keyDirection = "右";
				}
				if (key.getKeyCode() == KeyEvent.VK_SPACE) {
					space = true;
					if (snakeLength <= 10) {
						speed = 100;
					} else if (snakeLength > 10 && snakeLength <= 20) {
						speed = 150;
					} else if (snakeLength > 20 && snakeLength <= 30) {
						speed = 200;
					} else if (snakeLength > 30 && snakeLength <= 40) {
						speed = 250;
					}
				}
			}

			@Override
			public void keyReleased(KeyEvent key) {
				if (key.getKeyCode() == KeyEvent.VK_SPACE) {
					space = false;
				}
			}
		};
		this.addKeyListener(keyProcessor);

		startBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (startBt.getText().equals("开始游戏")) {
					xHead = xyRandom.nextInt(1, 74);
					yHead = xyRandom.nextInt(1, 37);
					xyMatrix[xHead][yHead] = 3;
					xSnake[0] = xHead;
					ySnake[0] = yHead;
					snakeLength = 1;
					startBt.setText("结束游戏");
					stopBt.setEnabled(true);
				} else {
					stop = false;
					stopBt.setText("暂停游戏");
					startBt.setText("开始游戏");
					stopBt.setEnabled(false);
					keyDirection = "";
					foodNum = 0;
					amountLabel.setText("现在长度：0000");

					for (int y = 1; y <= 37; y++) {
						for (int x = 1; x <= 74; x++) {
							xyMatrix[x][y] = 0;
						}
					}

					JOptionPane.showMessageDialog(null, "当前分数：" + snakeLength, "标题", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});

		stopBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (stopBt.getText().equals("暂停游戏")) {
					stopBt.setText("继续游戏");
				} else {
					stopBt.setText("暂停游戏");
				}
				stop = !stop;
			}
		});

		ruleBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				new RuleFrame().setVisible(true);
			}
		});

		aboutBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				new AboutUsFrame().setVisible(true);
			}
		});
	}

}
